

module AjaxHelper

  # user rate a deal - using ajax
  def rate_plus_ajax    
    # sanity check
    if (!params[:id] || !params[:rating] || !session[:user])
      render :text => "?"
      return
    end
    
    # find user & deal first    
    @user = User.find(session[:user][:id])
    @answer = Deal.find(params[:id])

    if (@user && @answer)
    
      # find user_dealrating first, search if something match us
      @userdeal = UserDealrating.find(:first, :conditions => "user_id = #{@user.id} and deal_id = #{@deal.id}")
      
      previousRating = 0
      
      if (@userdeal)
        # user rated this deal before, just modify the old record
        previousRating = @userdeal.deal_rating
        @userdeal.deal_rating = rating
        @userdeal.save
      else
        # user never rate this deal, create new record
        # create new user rating
        @userdeal = UserDealrating.new()
 
        # add rating to user rating
        if (@userdeal)
          @userdeal.user_id = @user.id
          @userdeal.deal_id = @deal.id
          @userdeal.deal_rating = rating
          @userdeal.save
        end
      end
      
      # check if it is successful (if it is, means this is valid rating, user doesn't save rating twice)
      if (previousRating>0)
        # we got previous rating, need to substract previous rating first
        # no need to add rating_num, since rating already exist
        @deal.rating -= previousRating
      else
        # we don't have previous rating, need to add rating number
        @deal.rating_num += 1
      end

      # if valid, then add to deal
      @deal.rating += params[:rating].to_i
      @deal.save
    end
    
    #rescue
      # do nothing for ajax    
    #ensure
      rating = 0.0
      rating = @deal.rating_num>0 ? @deal.rating / @deal.rating_num : 0;
      render :text => (rating).to_s+'('+@deal.rating_num.to_s+')'
  end
	
end